package ws

import (
	"api-fiber-gorm/model"
	"github.com/gofiber/websocket/v2"
	"log"
	"strconv"
)

type client struct {
	id string
} // Add more data to this type if needed
//var clients = make(map[*websocket.Conn]client)
var clients = make(map[string]*websocket.Conn) // Note: although large maps with pointer-like types (e.g. strings) as keys are slow, using pointers themselves as keys is acceptable and fast
var Register = make(chan *websocket.Conn)
var Broadcast = make(chan string)
var Msg = make(chan MessageTemplate)
var Unregister = make(chan *websocket.Conn)

func RunHub() {
	for {
		select {
		case connection := <-Register:
			//注册
			id := connection.Query("id")
			clients[id] = connection
			log.Println("connection registered:", id)
		//case message := <-Broadcast:
		case message := <-Msg:
			//发送消息
			log.Println("message received:", message)
			var ss = clients[message.AcceptId]
			var model2 model.Message
			var uid, _ = strconv.Atoi(message.UserId)
			model2.UserId = uid
			var sid, _ = strconv.Atoi(message.AcceptId)
			model2.SendId = sid
			var mType, _ = strconv.Atoi(message.MessageType)
			model2.MsgType = mType
			model2.IsRead = false
			model2.Data = message.Data
			messageService.SaveMessage(&model2)
			if ss != nil {
				if err := ss.WriteJSON(message); err != nil { //if err := ss.WriteMessage(websocket.TextMessage, []byte (message.Data)); err != nil {
					log.Println("write error:", err)
					ss.WriteMessage(websocket.CloseMessage, []byte{})
					ss.Close()
					delete(clients, message.AcceptId)
				}
			} else {
				//用户已经下线了
			}

		case connection := <-Unregister:
			id := connection.Query("id")
			log.Println("colse:", id)
			// Remove the client from the hub
			delete(clients, id) //connection
			log.Println("connection unregistered")
		}
	}
}
